/**
 * MCP Server Configuration Component
 * 
 * Form for adding new MCP servers
 */

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ChevronDown, Save, X } from 'lucide-react';
import type { McpServerConfig } from '@/api/mcp';
import * as mcpApi from '@/api/mcp';

interface MCPServerConfigProps {
  onSave: () => void;
  onCancel: () => void;
}

export function MCPServerConfig({ onSave, onCancel }: MCPServerConfigProps) {
  const [name, setName] = useState('');
  const [type, setType] = useState<'stdio' | 'sse' | 'http' | 'sdk'>('stdio');
  const [command, setCommand] = useState('');
  const [args, setArgs] = useState('');
  const [url, setUrl] = useState('');
  const [headers, setHeaders] = useState('');
  const [env, setEnv] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!name.trim()) {
      setError('请输入服务器名称');
      return;
    }

    try {
      setSaving(true);

      const config: McpServerConfig = { type };

      if (type === 'stdio') {
        if (!command.trim()) {
          setError('请输入命令');
          return;
        }
        config.command = command;
        if (args.trim()) {
          config.args = args.split(' ').filter(arg => arg.trim());
        }
        if (env.trim()) {
          try {
            config.env = JSON.parse(env);
          } catch {
            setError('环境变量格式错误，请使用 JSON 格式');
            return;
          }
        }
      } else if (type === 'sse' || type === 'http') {
        if (!url.trim()) {
          setError('请输入 URL');
          return;
        }
        config.url = url;
        if (headers.trim()) {
          try {
            config.headers = JSON.parse(headers);
          } catch {
            setError('请求头格式错误，请使用 JSON 格式');
            return;
          }
        }
      } else if (type === 'sdk') {
        config.name = name;
        config.version = '1.0.0';
      }

      await mcpApi.registerMcpServer(name, config);
      onSave();
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存失败');
    } finally {
      setSaving(false);
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>添加 MCP 服务器</CardTitle>
        <CardDescription>
          配置一个新的 Model Context Protocol 服务器
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Server Name */}
          <div className="space-y-2">
            <Label htmlFor="name">服务器名称</Label>
            <Input
              id="name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="例如: my-mcp-server"
              required
            />
          </div>

          {/* Server Type */}
          <div className="space-y-2">
            <Label>服务器类型</Label>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="w-full justify-between">
                  {type.toUpperCase()}
                  <ChevronDown className="ml-2 h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-full">
                <DropdownMenuItem onClick={() => setType('stdio')}>
                  STDIO - 标准输入输出
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setType('sse')}>
                  SSE - Server-Sent Events
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setType('http')}>
                  HTTP - HTTP 服务器
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setType('sdk')}>
                  SDK - SDK MCP 服务器
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>

          {/* Type-specific fields */}
          {type === 'stdio' && (
            <>
              <div className="space-y-2">
                <Label htmlFor="command">命令</Label>
                <Input
                  id="command"
                  value={command}
                  onChange={(e) => setCommand(e.target.value)}
                  placeholder="例如: node"
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="args">参数（用空格分隔）</Label>
                <Input
                  id="args"
                  value={args}
                  onChange={(e) => setArgs(e.target.value)}
                  placeholder="例如: server.js --port 3000"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="env">环境变量 (JSON 格式)</Label>
                <Textarea
                  id="env"
                  value={env}
                  onChange={(e) => setEnv(e.target.value)}
                  placeholder='{"API_KEY": "your-key"}'
                  rows={3}
                />
              </div>
            </>
          )}

          {(type === 'sse' || type === 'http') && (
            <>
              <div className="space-y-2">
                <Label htmlFor="url">URL</Label>
                <Input
                  id="url"
                  value={url}
                  onChange={(e) => setUrl(e.target.value)}
                  placeholder="例如: http://localhost:3001/mcp"
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="headers">请求头 (JSON 格式)</Label>
                <Textarea
                  id="headers"
                  value={headers}
                  onChange={(e) => setHeaders(e.target.value)}
                  placeholder='{"Authorization": "Bearer token"}'
                  rows={3}
                />
              </div>
            </>
          )}

          {type === 'sdk' && (
            <div className="p-4 bg-muted rounded-md">
              <p className="text-sm text-muted-foreground">
                SDK MCP 服务器是内置的工具服务器，由应用程序直接管理。
                这种类型的服务器无需额外配置。
              </p>
            </div>
          )}

          {/* Error Message */}
          {error && (
            <div className="p-3 bg-destructive/10 text-destructive rounded-md text-sm">
              {error}
            </div>
          )}

          {/* Actions */}
          <div className="flex gap-2 justify-end">
            <Button
              type="button"
              variant="outline"
              onClick={onCancel}
              disabled={saving}
            >
              <X className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button type="submit" disabled={saving}>
              <Save className="w-4 h-4 mr-2" />
              {saving ? '保存中...' : '保存'}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
